package com.powergisol.gis.service.impl;

import com.powergisol.gis.datasources.MyJdbcTemplate;
import com.powergisol.gis.service.SearchService;
import com.powergisol.gis.vo.Column;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private MyJdbcTemplate myJdbcTemplate;

    private  static Map<Integer,String> types = null;



    @Override
    public List<Column> getColumns(String tableName) {

        String sql = "SELECT DISTINCT DATA_TYPE, TABLE_NAME,COLUMN_NAME,IS_NULLABLE,COLUMN_COMMENT FROM INFORMATION_SCHEMA.Columns WHERE table_name=? "+
               "AND COLUMN_NAME IN(\"ZKBH\",\"ZKLX\",\"ZKX\",\"ZKY\",\"ZKBG\",\"ZKSD\",\"ZKZJ\",\"ZKKSRQ\",\"ZKZZRQ\",\"TCCDSD\",\"TCXH\",\"TCBH\",\"TCZCBH\",\"TCYCBH\",\"TCCYCBH\"," +
                "\"TCSDCY\",\"TCDZSD\",\"TCDZCY\",\"TCDCHD\",\"TCHD\",\"TCLM\",\"TCMC\",\"TCMS\",\"SWSD\",\"SWCSRQ\",\"SWDXSW\",\"GCMC\",\"GCBH\",\"GCRQ\",\"GCFZR\")"+
               " order By ORDINAL_POSITION";
        List<Column> list = myJdbcTemplate.getJdbcOperations().query(sql,new RowMapper<Column>(){

            @Override
            public Column mapRow(ResultSet rs, int rowNum) throws SQLException {

                Column column = new Column();
                column.setName(rs.getString("column_name"));
                //处理注释里面的括号
                String comment = rs.getString("column_comment");
                int b ;
                if((b = comment.indexOf("("))!=-1||((b = comment.indexOf("（"))!=-1)){
                    comment = comment.substring(0,b);
                }
                column.setLabel(comment);
                return column;
            }
        },tableName);

        return list;
    }

    public static void main(String[] args) {
        SearchServiceImpl searchService = new SearchServiceImpl();
        List<Column> list = searchService.getColumns("tab_data_detail");
        System.out.println(list);
    }

    /**
     * 获取java.sql.Types 所有属性值对应的属性名，通过反射将属性值作为key,属性名作为value
     * @param clazz
     * @return
     */
    private Map<Integer ,String> getAllFields(Class clazz){
        Map<Integer ,String> resutlMap = new LinkedHashMap<Integer ,String>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                resutlMap.put(field.getInt(field.getName()), field.getName());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return resutlMap;
    }
}
